package com.dev.op.controller;

import com.dev.op.VO.ResultVO;
import com.dev.op.entity.Result;
import com.dev.op.entity.Submission;
import com.dev.op.VO.TaskVO;
import com.dev.op.service.RedisService;
import com.dev.op.service.SubmissionService;
import com.dev.op.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/internal")
@Transactional
public class InternalController {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    SubmissionService submissionService;

    @Autowired
    RedisService redisService;
    /**
     *
     * @param taskVO
     * 总结 聚合器返回的结果，插入submission表
     */
    @PostMapping("/judge/result")
    public ResultVO<String> judgeResult(@RequestBody TaskVO taskVO) {
        //获取之前的元数据
        TaskVO meta = redisUtil.getSubmissionMetaData(taskVO.getSubmissionId());

        int acceptedCnt = 0;
        String finalStat = "";
        double avgMem = 0;
        double avgTime = 0;
        String input = "";
        String output = "";
        String expectedOutput = "";
        String error = "";
        //统计 ACCEPTED 和 其他的个数
        for(Result result : taskVO.getResults()) {
            if(!result.getStatus().equals("ACCEPTED")){
                finalStat = result.getStatus();
                input = result.getInput();
                output = result.getOutput();
                expectedOutput = result.getExpected();
                error = result.getError();
            }
            else{
                avgMem += Double.parseDouble(result.getMem());
                avgTime += Double.parseDouble(result.getTime());
                acceptedCnt++;
            }
        }
        //接收
        if(finalStat.isEmpty()){
            finalStat = "ACCEPTED";
            avgMem = avgTime / acceptedCnt;
            avgTime = avgTime / acceptedCnt;
        }else{
            avgMem = 0;
            avgTime = 0;
        }

        Submission submission = new Submission(
                meta.getSubmissionId(),
                Integer.parseInt(meta.getSubmitterId()),
                meta.getProblemId(),
                meta.getProblemTitle(),
                meta.getCode(),
                meta.getLanguage(),
                input,
                expectedOutput,
                output,
                error,
                String.valueOf(avgMem),
                String.valueOf(avgTime),
                finalStat,
                String.valueOf((double) acceptedCnt / (double) meta.getTestCaseCnt()),
                meta.getSubmitDate()
        );
        submissionService.save(submission);
        redisService.saveSubmissionResult(submission,36000);
        return ResultVO.success("good");
    }
}
